package fpzhan.plane.program.connect;

import fpzhan.plane.program.describe.ComposeComment;
import fpzhan.plane.program.exception.CannotLoopException;
import fpzhan.plane.program.function.LoopParamFunction;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;

public class LoopMixCodeBlockConnect extends MixCodeBlockConnect{


    public LoopMixCodeBlockConnect(CodeBlockContext context, ChainCodeBlockConnect source) {
        super(context, source);
        this.aloneCodeBlockCompose=new LoopCodeBlockCompose(new ChainCodeBlockConnect(context,this));

    }


    protected <T> ComposeComment<LoopCodeBlockCompose,ChainCodeBlockConnect> loop(String getKey , String loopKey, String loopIndex, String loopSize){
        return loop(param -> {
            Object getObject = param.get(getKey);
            if(getObject.getClass().isArray()){
                T [] array = (T [] )getObject;
                return Arrays.asList(array);
            }else if(getObject instanceof Collection){
                return   (Collection) getObject ;
            }else{
                throw new CannotLoopException();
            }
        },loopKey,loopIndex,loopSize);
    }

    protected ComposeComment<LoopCodeBlockCompose,ChainCodeBlockConnect> loop(LoopParamFunction function, String loopKey, String loopIndex, String loopSize){
        ((LoopCodeBlockCompose)this.aloneCodeBlockCompose).setLoopElementKey(loopKey);
        ((LoopCodeBlockCompose)this.aloneCodeBlockCompose).setLoopIndexKey(loopIndex);
        ((LoopCodeBlockCompose)this.aloneCodeBlockCompose).setLoopSizeKey(loopSize);
        ((LoopCodeBlockCompose)this.aloneCodeBlockCompose).setLoopParamFlow(function);
        return new ComposeComment(((LoopCodeBlockCompose)this.aloneCodeBlockCompose),((LoopCodeBlockCompose)this.aloneCodeBlockCompose).getChild());
    }



    protected ChainCodeBlockConnect loopEnd( ){
        ((ChainCodeBlockConnect)getSource()).addChainBlocks(Collections.singletonList(this.aloneCodeBlockCompose));
        return (ChainCodeBlockConnect)getSource();
    }
}
